<?php

    //重启脚本
    //$restart_cmd = "service rabbitmq-server restart";
    $restart_cmd = "/etc/init.d/rabbitmq-server restart &";

    //日志保存位置
    $log_path = '/home/zyyt/log/rabbitmq/check_mq.log';

    $conn_args = [
        'host' => '127.0.0.1',  //rabbitmq 服务器host
        'port' => 5672,         //rabbitmq 服务器端口
        'login' => 'guest',     //登录用户
        'password' => 'guest',   //登录密码
        'vhost' => '/'         //虚拟主机
    ];

    $config = [
        'exchangeName' => 'uweibomatchv4',
        'eqeueName' => 'check_mq',
        'eqeueName_key' => 'check_mq_key'
    ];

    $e_name = $config['exchangeName'];
    $q_name = $config['eqeueName'];
    $k_name = $config['eqeueName_key'];

    try {
        $conn = new AMQPConnection($conn_args);
        $connect = $conn->connect();
        if (!$connect) {
            //执行重启脚本
            echo "connect error";
            $msg = date('Y-m-d H:i:s') . " connect error  连接rabbitmq服务失败. \n";
            error_log($msg, 3, $log_path);
            exec($restart_cmd);
            return;
        }

    }catch(Exception $e){

        echo "service error";
        $msg = date('Y-m-d H:i:s') . " service error  rabbitmq服务已经停止. \n";
        error_log($msg, 3, $log_path);
        exec($restart_cmd);
        return;

    }

    //生产
    $channel = new AMQPChannel($conn);

    // 创建交换机
    $ex = new AMQPExchange($channel);
    $ex->setName($e_name);
    $ex->setType(AMQP_EX_TYPE_DIRECT); // 设置路由规则
    $ex->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); // 这个要创建的交换机是否持久化
    $ex->declareExchange(); // 执行创建， 不要用declare(), 已经过时了，会报错的

    // 创建队列
    $q = new AMQPQueue($channel);
    $q->setName($q_name);
    $q->setFlags(AMQP_DURABLE | AMQP_AUTODELETE); // 同上
    $q->declareQueue(); // 同上
    $q->bind($e_name, $k_name);

    $ex = new AMQPExchange($channel);
    $ex->setName($e_name);



    //启动消费脚本
    echo "start get_mq.php \n";
    $get_cmd = "/usr/bin/php /home/zyyt/get_mq.php &";
    $msg =  date('Y-m-d H:i:s')." get mq start  启动取数据脚本. \n";
    error_log($msg, 3, $log_path);
    //exec($get_cmd);
    pclose(popen($get_cmd, 'r'));

    echo "start publish \n";
    $msg =  date('Y-m-d H:i:s')." start publish  开始向队列推送数据. \n";
    error_log($msg, 3, $log_path);

    $message = '123';
    $ex->publish($message, $k_name);

    echo "end publish \n\n";
    $msg =  date('Y-m-d H:i:s')." end publish  完成向队列推送数据. \n";
    error_log($msg, 3, $log_path);

    return;

?>
